package com.yfp.tissue.service.impl;

import cn.hutool.core.util.StrUtil;
import com.yfp.common.core.domain.R;
import com.yfp.common.security.utils.SecurityUtils;
import com.yfp.system.api.domain.SysRole;
import com.yfp.system.api.domain.SysUser;
import com.yfp.tissue.domain.Dto.CompanyDto;
import com.yfp.tissue.domain.Dto.UserReqDto;
import com.yfp.tissue.domain.SysDeptCity;
import com.yfp.tissue.domain.entity.*;
import com.yfp.tissue.domain.vo.CompanyListVO;
import com.yfp.tissue.domain.vo.CompanyVO;
import com.yfp.tissue.mapper.*;
import com.yfp.tissue.mapper.*;
import com.yfp.tissue.service.CommonService;
import com.yfp.tissue.service.SysDeptCityService;
import com.yfp.tissue.service.UserService;
import com.yfp.tissue.domain.entity.*;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @PROJECT_NAME: ydyfp
 * @DESCRIPTION:
 * @USER: xiaohuya
 * @DATE: 2023/12/20 21:15
 */

@Service
@Slf4j

public class CommonServiceImpl implements CommonService {
    @Resource
    private CompanyMapper companyMapper;
    @Resource
    private AreaMapper areaMapper;
    @Resource
    private PositionMapper positionMapper;
    @Resource
    private SysUserRoleMapper sysUserRoleMapper;
    @Resource
    private PositionTypeMapper positionTypeMapper;
    @Resource
    private RouteMapper routeMapper;
    @Resource
    private DistrictMapper districtMapper;
    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private UserService userService;
    @Resource
    private SysUserCompanyMapper sysUserCompanyMapper;
    @Resource
    private SysDeptCityService sysDeptCityService;

    @Override
    public R queryCompany(String companyId, String enable) {
        CompanyDto companyDto = new CompanyDto();
        // companyDto.setCompanyId(companyId);
        companyDto.setEnabled(enable);
        List<CompanyVO> companyVOS = companyMapper.queryByReq(companyDto);
        return R.ok(companyVOS);
    }

    @Override
    public R queryArea(String companyId, String enable) {
        Area area = new Area();
        area.setCompanyId(companyId);
        area.setEnabled("1");
        List<Area> areas = areaMapper.queryAll(area);
        return R.ok(areas);
    }

    @Override
    public R queryRoute(String areaId, String enable) {
        Route route = new Route();
        route.setAreaId(areaId);
        route.setEnable("1");
        List<Route> routes = routeMapper.queryArea(route);
        return R.ok(routes);
    }

    @Override
    public R queryPosition(String routeId, String enable) {
        List<Position> positions = positionMapper.queryById(routeId, enable);
        return R.ok(positions);
    }

    @Override
    public R queryDistrict() {
        // 区
        List<District> countys = districtMapper.queryCounty();
        // 市
        List<District> citys = districtMapper.queryCity();
        // 省
        List<District> districts = districtMapper.queryProvince();

        citys.stream().forEach(e -> {
            List<District> list = countys.stream().filter(cs -> cs.getId().equals(e.getValue())).toList();
            e.setChildren(list);
        });
        districts.stream().forEach(e -> {
            List<District> list = citys.stream().filter(cs -> cs.getId().equals(e.getValue())).toList();
            e.setChildren(list);
        });
        return R.ok(districts);
    }

    @Override
    public R queryPositionType(String routeId, String enable) {
        PositionType positionType = new PositionType();
        if (Objects.nonNull(routeId)) {
            Route route = routeMapper.getById(routeId);
            positionType.setCityName(route.getCityName());
        }
        positionType.setEnable(enable);
        List<PositionType> positionTypes = positionTypeMapper.queryById(positionType);
        return R.ok(positionTypes);
    }

    @Override
    public R queryUser(String companyId, String cityName, String type) {
        if (Objects.isNull(companyId)) {
            return R.ok();
        }
        if (Objects.isNull(cityName)) {
            return R.ok();
        }
        if (Objects.isNull(type)) {
            return R.ok();
        }
        // 角色权限字符定义
        // 公司负责人的权限字符规则   自定义_companyManager
        // 区域负责人的权限字符规则    自定义_areaManager
        // 线路负责人的权限字符规则    自定义_roteManager
        // 点位客服人员的权限字符规则    自定义_postionCustomer
        // 维修负责人 员的权限字符规则   自定义_maintenance
        UserReqDto userReqDto = new UserReqDto();
        if (type != null && type.equals("area")) {
            // types = "区域负责人";
            userReqDto.setRoleKey("_areaManager");
        } else if (type != null && type.equals("route")) {
            // types = "线路负责人";
            userReqDto.setRoleKey("_roteManager");
        } else if (type != null && type.equals("repair")) {
            // types = "设备维修员";
            userReqDto.setRoleKey("_maintenance");
        } else if (type != null && type.equals("positionCustomer")) {
            // types = "点位客服人员";
            userReqDto.setRoleKey("_postionCustomer");
        } else if (type != null && type.equals("company")) {
            // types = "公司负责人";
            userReqDto.setRoleKey("_companyManager");
        }

        if (Objects.nonNull(companyId)) {
            Company company = companyMapper.queryById(companyId);
            if (Objects.nonNull(company)) {
                cityName = StrUtil.subBefore(cityName, "/", false);
                SysDeptCity sysDeptCity = sysDeptCityService.getByDeptIdAndCityName(company.getDeptId(), cityName);
                if (Objects.isNull(sysDeptCity)) {
                    return R.ok();
                }
                userReqDto.setCityNameList(Collections.singletonList(sysDeptCity.getCityName()));
                List<SysUser> byDeptIdAndCitys = userService.findByDeptIdAndCitys(userReqDto);
                return R.ok(byDeptIdAndCitys);
            }
        }
        return R.ok();
    }

    @Override
    public R queryParentCompany(String companyId) {
        List<CompanyVO> companyVOS = null;
        SysUser sysUser = sysUserMapper.selectUserByUserName(SecurityUtils.getUsername());
        List<SysRole> roles = sysUser.getRoles();
        List<String> collect = roles.stream().map(SysRole::getRoleName).collect(Collectors.toList());
        if (collect.contains("超级管理员")) {

            companyVOS = companyMapper.queryParenCompany(null);
        } else {
            companyVOS = companyMapper.queryParenCompany(companyId);

        }

        return R.ok(companyVOS);
    }

    @Override
    public R queryCompanyList(String roleId) {
        List<CompanyListVO> companyLists = companyMapper.queryCompanyList();
        List<CompanyListVO> areaLists = areaMapper.queryCompanyList(companyLists.stream().map(CompanyListVO::getId).collect(Collectors.toList()));
        List<CompanyListVO> routeLists = routeMapper.queryCompanyList(areaLists.stream().map(CompanyListVO::getId).collect(Collectors.toList()));
        List<CompanyListVO> positions = positionMapper.queryCompanyList(routeLists.stream().map(CompanyListVO::getId).collect(Collectors.toList()));
        recursion(routeLists, positions);
        recursion(areaLists, routeLists);
        recursion(companyLists, areaLists);
        HashMap<String, Object> companyMap = new HashMap<>();
        companyMap.put("companyLists", companyLists);
        List<SysUserCompany> sysUserCompanys = sysUserCompanyMapper.queryById(roleId);
        List<String> list = sysUserCompanys.stream().map(SysUserCompany::getId).toList();
        companyMap.put("checkdKeys", list);

        System.out.println(companyMap);
        return R.ok(companyMap);
    }

    public static List<CompanyListVO> recursion(List<CompanyListVO> up, List<CompanyListVO> ut) {
        up.forEach(e -> {
            List<CompanyListVO> companyListVOS = new ArrayList<>();
            ut.forEach(u -> {
                if (e.getId().equals(u.getRelevanceId())) {
                    companyListVOS.add(u);
                }
            });
            e.setCompanyListVOS(companyListVOS);
        });
        return up;
    }


}
